#@layout()
#define main()
<input type="hidden" class="layui-input" id="orderId" name="sellOrder.orderId" value="#(sellOrder.order_id??)"/>
<div class="layui-row layui-col-space1 task-row">
	#@colStart("客户",3)
	<input id="customerId" type="hidden" class="layui-input" placeHolder="必填" name="sellOrder.customerId" value="#(sellOrder.customer_id??)"/>
	<input id="customerName" type="text" class="layui-input" placeHolder="必填" name="sellOrder.customerName" value="#(sellOrder.customer_name??)"/>
	#@colEnd()
	#@colStart("开单人",3)
	<input id="originator" type="hidden" placeHolder="必填" class="layui-input" name="sellOrder.originator" value="#(sellOrder.originator??)" />
	<input id="originatorName" type="text" placeHolder="必填" class="layui-input" name="sellOrder.originatorName" value="#(sellOrder.user_name??)" />
	#@colEnd()
	#@colStart("开单时间",3)
	<input id="originatTime" type="text" lay-verType='tips' placeHolder="请选择时间" class="layui-input" name="sellOrder.originatTime" value="#(sellOrder.originat_time??)" />
	#@colEnd()
	#@colStart("发货时间",3)
	<input id="planTime" type="text" lay-verType='tips' placeHolder="请选择时间" class="layui-input" name="sellOrder.planTime" value="#(sellOrder.plan_time??)" />
	#@colEnd()
</div>

<div class="layui-row layui-col-space1 task-row">
	<!--#@colStart("实际发货时间",3)-->
	<!--<input id="actualTime" type="text" lay-verType='tips' class="layui-input" name="sellOrder.actualTime" value="#(sellOrder.actual_time??)" />-->
	<!--#@colEnd()-->
	#@colStart('结账方式',3)
	<select id="settleWay" name="sellOrder.settleWay" class="layui-input" lay-search>
		#for(data:orderSettleWayMap)
		<option value="#(data.key??)" #if(sellOrder.settle_way??==data.key) selected="selected" #end>#(data.value??)</option>
		#end
	</select>
	#@colEnd()
	#@colStart("总计金额",3)
	<input id="totalAmount" type="text" lay-verType='tips' placeHolder="请输入数字" class="layui-input" name="sellOrder.totalAmount" value="#(sellOrder.total_amount??)" />
	#@colEnd()
	#@colStart("是否含发票",3)
	<select id="containBill" name="sellOrder.containBill" class="layui-input" lay-search>
		#for(data:orderContainBillMap)
		<option value="#(data.key??)" #if(sellOrder.containBill??==data.key) selected="selected" #end>#(data.value??)</option>
		#end
	</select>
	#@colEnd()
	#@colStart("税率",3)
	<input id="taxRate" type="text" lay-verType='tips' placeHolder="请输入数字" class="layui-input" name="sellOrder.taxRate" value="#(sellOrder.tax_rate??)" />
	#@colEnd()
</div>

<div class="layui-row layui-col-space1 task-row">
	<!--#@colStart('单据状态',3)-->
	<!--<select id="status" name="sellOrder.status" class="layui-input" lay-search>-->
	<!--<option value="">-&#45;&#45;请选择-&#45;&#45;</option>-->
	<!--#for(data:orderStatusMap)-->
	<!--<option value="#(data.key??)" #if(sellOrder	.status??==data.key) selected="selected" #end>#(data.value??)</option>-->
	<!--#end-->
	<!--</select>-->
	<!--#@colEnd()-->
	#@colStart("物流单号",3)
	<input id="logisticsNum" type="text" lay-verType='tips' class="layui-input" name="sellOrder.taxRate" value="#(sellOrder.logistics_num??)" />
	#@colEnd()
	#@colStart("运费类型",3)
	<select id="carriageType" name="sellOrder.carriageType" class="layui-input" lay-search>
		#for(data:orderCarriageTypeMap)
		<option value="#(data.key??)" #if(sellOrder.carriageType??==data.key) selected="selected" #end>#(data.value??)</option>
		#end
	</select>
	#@colEnd()
	#@colStart("运费",3)
	<input id="carriage" type="text" lay-verType='tips' placeHolder="请输入数字" class="layui-input" name="sellOrder.carriage" value="#(sellOrder.carriage??)" />
	#@colEnd()
	#@colStart("实际运费",3)
	<input id="realCarriage" type="text" lay-verType='tips' placeHolder="请输入数字" class="layui-input" name="sellOrder.realCarriage" value="#(sellOrder.carriage??)" />
	#@colEnd()
</div>
<div class='layui-row f-index-toolbar'>
	<div class='layui-col-xs12'>
		<div class="layui-btn-group">
			<button id='addRow' class="layui-btn layui-btn-normal layui-btn-sm">
				<i class="layui-icon">&#xe608;</i> 新增一行
			</button>
		</div>
	</div>
</div>

<!-- 表格列表 -->
<div class="layui-row  f-index-toolbar">
	<div class="layui-col-xs12">
		<table id="maingrid" lay-filter="maingrid"></table>
	</div>
</div>

<div class='layui-row f-index-toolbar'>
	<div class='layui-col-xs12'>
		<div class="layui-btn-group">
			<button id='addRow2' class="layui-btn layui-btn-normal layui-btn-sm">
				<i class="layui-icon">&#xe608;</i> 新增一行
			</button>
		</div>
	</div>
</div>

<!-- 表格列表 -->
<div class="layui-row  f-index-toolbar">
	<div class="layui-col-xs12">
		<table id="payDetail" lay-filter="maingrid"></table>
	</div>
</div>


<div class="text-center">
	<button type="button" id="saveBtn" name="btnSave" class="layui-btn" data-type="save"><i class="layui-icon layui-icon-ok-circle"></i>保存</button>
	<button type="button" id="cancelBtn" name="btnCancel" class="layui-btn layui-btn-primary">取消</button>
</div>


<!-- 	每行的操作按钮 -->
<script type="text/html" id="bar_maingrid">
	<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delRow">移除</a>
</script>
<!-- 	每行的操作按钮 -->
<script type="text/html" id="bar_payDetail">
	<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delRow2">移除</a>
</script>
#end

#define js()
<script>
	$(function(){
		// 初始化获取订单项列表
		var url = '#(path)/erp/order/sellDetail/list?orderId='+$("#orderId").val();
		var detailList=[];
		$.post(url,function(data){
			console.log(data);
			detailList = data.list;
			debugger;
			for(var i=0;i<detailList.length;i++){
				detailList[i].tempId = i;
			}
			var item = {};
			item.title='订单项';
			item.dataId='detail_id';
			item.gridDivId ='maingrid';
			initGrid({id : 'maingrid'
				,elem : '#maingrid'
				,cellMinWidth: 80
				,cols : [ [
					{title: '主键',field : 'detail_id',width : 35,checkbox : true},
					{title: '序号',type:'numbers',width:35},
					{title: '物品', field: 'entity_name', event: 'setEntity',edit:'text' },
					{title: '所属上级', field: 'par_entity_name'},
					{title: '适用车型', field: 'car_type'},
					{title: '计量单位', field: 'unit',edit:'text'},
					{title: '数量', field: 'amount',edit:'text'},
					{title: '价格', field: 'price',edit:'text'},
					{title: '折扣', field: 'discount',edit:'text'},
					{title: '金额', field: 'sum_money',edit:'text'},
					{title: '备注', field: 'remark', edit: 'text'},
					{title: '操作', field: 'tempId', fixed: 'right', width : 80, align : 'left',toolbar : '#bar_maingrid'} // 这里的toolbar值是模板元素的选择器

				] ]
				,data:detailList
				,where:{"object":"sys_tree","primaryKey":item.dataId}
				,searchForm : 'searchForm'
			},{
				setEntity: setEntity,
				delRow:delRow,
				setPayCode:setPayCode,
				delRow2:delRow2
			}, item);
		});

		// 初始化获取支付项列表
		var payUrl = '#(path)/erp/order/incomeDetail/list?orderId='+$("#orderId").val();
		var payList = [];
		$.post(payUrl,function(data){
			payList = data.list;
			var args = {};
			args.title='付款明细';
			args.dataId='detail_id';
			args.gridDivId ='payDetail';
			initGrid({id : 'payDetail'
				,elem : '#payDetail'
				,cellMinWidth: 80
				,cols : [ [
					{title: '主键',field : 'detail_id',width : 35,checkbox : true},
					{title: '序号',type:'numbers',width:35},
					{title: '支付编码', field: 'pay_code', event: 'setPayCode'},
					{title: '支付类型', field: 'pay_type' },
					{title: '账号', field: 'account' },
					{title: '支付金额', field: 'sum_money',edit:'text'},
					<!--{title: '支付方', field: 'pay_men',edit:'text'},-->
					<!--{title: '收入方', field: 'receive_men',edit:'text'},-->
					<!--{title: '交易时间', field: 'trans_time',edit:'text'},-->
					{title: '操作', field: 'tempId', fixed: 'right', width : 80, align : 'left',toolbar : '#bar_payDetail'} // 这里的toolbar值是模板元素的选择器

				] ]
				,data:payList
				,where:{"object":"sys_tree","primaryKey":gridArgs.dataId}
				,searchForm : 'searchForm'
			},{
				setPayCode:setPayCode,
				delRow2:delRow2
			}, args);
		});

		$("#addRow").click(function(){
			var oldData = table.cache['maingrid'];
			debugger;
			console.log(oldData);
			var newRow = {tempId: new Date().valueOf(),detail_id: '', entity_id: null,par_entity: null,unit: '个',amount: 0,price: 0, discount: 0, sum_money: 0};
			oldData.push(newRow);
			table.reload('maingrid',{
				data : oldData
			});
      	});
		$("#addRow2").click(function(){
			var oldData = table.cache['payDetail'];
			console.log(oldData);
			var newRow = {tempId: new Date().valueOf(),detail_id: '', pay_code: null,sum_money: 0,pay_men: null,receive_men: null,trans_time: 0};
			oldData.push(newRow);
			table.reload('payDetail',{
				data : oldData
			});
		});

		$('#cancelBtn').click(function(){
			var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
			parent.layer.close(index); //再执行关闭
		});

		$("#saveBtn").click(function(){
			var orderId = $('#orderId').val();
			if(orderId.length == 0){
				layer.msg("订单不存在！",{icon:2});
				return ;
			}
			// 输入框判断
			var customerId = $('#customerId').val();
			if(customerId.length == 0){
				layer.msg("请选择客户！",{icon:2});
				return ;
			}
			var originator = $('#originator').val();
			if(originator.length == 0){
				layer.msg("请选择开单人！",{icon:2});
				return ;
			}
			var originatTime = $('#originatTime').val();
			if(originatTime.length == 0){
				layer.msg("请选择开单时间！",{icon:2});
				return ;
			}
			var planTime = $('#planTime').val();
			if(planTime.length == 0){
				layer.msg("请选择发货时间！",{icon:2});
				return ;
			}
			var settleWay = $('#settleWay').val();
			if(settleWay.length == 0){
				layer.msg("请选择结账方式！",{icon:2});
				return ;
			}
			var totalAmount = $('#totalAmount').val();
			if(totalAmount.length == 0){
				layer.msg("请输入总计金额！",{icon:2});
				return ;
			}
			var containBill = $('#containBill').val();
			if(containBill.length == 0){
				layer.msg("请选择是否含发票！",{icon:2});
				return ;
			}
			var carriageType = $('#carriageType').val();
			if(carriageType.length == 0){
				layer.msg("请选择运费类型！",{icon:2});
				return ;
			}

			var detailList = table.cache['maingrid'];
			console.log(detailList);
			var payList = table.cache['payDetail'];
			console.log(payList);
			debugger
			var param = {
				orderId:orderId,
				customerId:customerId,
				originator:originator,
				originatTime:originatTime,
				planTime:planTime,
				settleWay:settleWay,
				totalAmount:totalAmount,
				containBill:containBill,
				taxRate:$('#taxRate').val(),
				logisticsNum:$('#logisticsNum').val(),
				carriageType:$('#carriageType').val(),
				carriage:$('#carriage').val(),
				realCarriage:$('#realCarriage').val(),
				detailList: JSON.stringify(detailList),
				payList:JSON.stringify(payList)
			}
			console.log(param)
			layer.confirm('确定要提交吗？',{icon: 3, title:'提示'},function(index){
				$.post("#(path)/erp/order/sell/updateOrder",param,function(feedback) {
					setTimeout('window.location.reload()',500);
					if (feedback.success) {
						layer.close(index);
						var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
						parent.layer.close(index); //再执行关闭
						windows.location.href="#(path)/erp/order/purchase/index";
					} else {
						$(".layui-laypage-btn").click();
						layer.alert(feedback.msg);
					}
				});
			});

		})

	})


	function setEntity(obj){
		var entityId ; var entityName; var carType;
		var par_entity; var par_entity_id;
		openDialogReturn("物品树形展示窗口","#(path)/erp/info/entity/renderEntityTree",false,null,null,null,function(res){
             entityId = res.entityId;
             entityName = res.entityName;

			debugger;
			// 后台发起请求，查询物品信息
			$.ajax({
                type: 'post',
                url: '#(path)/erp/info/entity/getInfo',
                data: {
                    entityId:entityId
                },
                async: false,
                dataType: 'json',
                success: function (result) {
                	debugger;
                    carType = result.carType;	// 获取 适用车型

                }
            });
            // 后台发起请求，查询父级物品信息
            $.ajax({
                type: 'post',
                url: '#(path)/erp/info/entity/getParent',
                data: {
                    entityId:entityId
                },
                async: false,
                dataType: 'json',
                success: function (result) {
                    par_entity = result.entity_name;	// 修改表格值
                    par_entity_id = result.entity_id;	// 修改表格值

                }
            });
            var oldData = table.cache['maingrid'];
            for(var i=0, row; i < oldData.length; i++){
				row = oldData[i];
				if(row.tempId == obj.data.tempId){
					debugger;
					row.entity_id = entityId;
					row.entity_name = entityName;
					row.par_entity_name = par_entity;
					row.par_entity = par_entity_id;
					row.car_type = carType;
				}
				continue;
			}
			table.reload('maingrid',{
				data : oldData
			});
        });

	}

	function setPayCode(obj){
		debugger
		var payCode ,account,payType
		openDialogReturn("支付方式选择窗口","#(path)/erp/info/payment/index",false,null,null,null,function(res){
             payCode = res.payCode;
			 account = res.account;
			 payType = res.payType;
            var oldData = table.cache['payDetail'];
            for(var i=0, row; i < oldData.length; i++){
				row = oldData[i];
				if(row.tempId == obj.data.tempId){
					debugger;
					row.pay_code = payCode;
					row.account = account;
					row.pay_type = payType;
				}
				continue;
			}
			table.reload('payDetail',{
				data : oldData
			});
        });

	}

	function delRow(obj){
		debugger;
		obj.del(); // 删除当前行
		var oldData = table.cache['maingrid'];
		for(var i=0, row; i < oldData.length; i++){
			row = oldData[i];
			if(row.length==0){
				oldData.splice(i, 1);    //删除一项
			}

		}
		table.reload('maingrid',{
				data : oldData
		});
	}
	function delRow2(obj){
		debugger
		obj.del(); // 删除当前行
		var oldData = table.cache['payDetail'];
		for(var i=0, row; i < oldData.length; i++){
			row = oldData[i];
			if(row.length==0){
				oldData.splice(i, 1);    //删除一项
			}
		}
		table.reload('payDetail',{
				data : oldData
		});
	}

</script>

#end

<!-- 时间控件 -->
#define layuiFunc()

//监听单元格编辑
    table.on('edit(maingrid)', function(obj){
		debugger;
        var value = obj.value //得到修改后的值
            ,data = obj.data //得到所在行所有键值
            ,field = obj.field; //得到字段
		if(field == 'amount'){
			data.sum_money = data.amount * data.price;
			obj.update({'sum_money':data.sum_money});
		}else if(field == 'price'){
			data.sum_money = data.amount * data.price;
			obj.update({'sum_money':data.sum_money});
		}
		// 更新总金额
		var totalAmount = 0;
		var table_data = table.cache['maingrid'];
		for(var i=0, row; i < table_data.length; i++){
			var temp = table_data[i];
			totalAmount += parseInt(temp.sum_money);
		}
		$('#totalAmount').val(totalAmount);

	});

	//监听单元格编辑
    table.on('edit(payDetail)', function(obj){
        var value = obj.value //得到修改后的值
            ,data = obj.data //得到所在行所有键值
            ,field = obj.field; //得到字段
		obj.update(field) //修改当前行数据

    });

	// 客户输入框点击事件
    $("#customerName").on('click',function () {
        openDialogReturn("客户选择窗口","#(path)/erp/info/customer/index",false,null,null,null,function (res) {
			debugger;
			var customerId = res.customerId;
			var customerName = res.customerName;
			$("#customerId").val(customerId);
			$("#customerName").val(customerName);
        });
    })
	// 起单人输入框点击事件
    $("#originatorName").on('click',function () {
        openDialogReturn("开单人选择窗口","#(path)/portal/core/sysUser/index",false,null,null,null,function (res) {
            var userCode = res.userCode;
            var userName = res.userName;
            $("#originator").val(userCode);
            $("#originatorName").val(userName);
        });
    })

    laydate.render({
        elem: '#originatTime',
        type: 'datetime'
    });
    laydate.render({
        elem: '#planTime',
        type: 'datetime'
    });
    laydate.render({
        elem: '#actualTime',
        type: 'datetime'
    });

#end

